<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="概述 AVL树得名于它的发明者G.M. Adelson-Velsky和E.M. Landis,它是最先发明的自平衡二叉查找树. 在AVL树中任何节点的两个子树的高度最大差别为一.并且,查找、插入、删除等操作在平均和最坏情况下都是O(log n). AVL树的基本操作都与二叉查找树的算法一致,只有在插入、删除等这种会改变树的平衡性的操作需要使用一些旋转操作来修正树的平衡性. 平衡因子 节点的平衡因子">
<meta property="og:type" content="article">
<meta property="og:title" content="平衡查找树之AVL树">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2017/04/08/2017-4-08-avl_tree/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="概述 AVL树得名于它的发明者G.M. Adelson-Velsky和E.M. Landis,它是最先发明的自平衡二叉查找树. 在AVL树中任何节点的两个子树的高度最大差别为一.并且,查找、插入、删除等操作在平均和最坏情况下都是O(log n). AVL树的基本操作都与二叉查找树的算法一致,只有在插入、删除等这种会改变树的平衡性的操作需要使用一些旋转操作来修正树的平衡性. 平衡因子 节点的平衡因子">
<meta property="og:locale">
<meta property="article:published_time" content="2017-04-08T10:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="2017">
<meta property="article:tag" content="Algorithms">
<meta property="article:tag" content="Tree">
<meta property="article:tag" content="数据结构">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/04/08/2017-4-08-avl_tree/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>平衡查找树之AVL树 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B3%E8%A1%A1%E5%9B%A0%E5%AD%90"><span class="nav-number">2.</span> <span class="nav-text">平衡因子</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%97%8B%E8%BD%AC"><span class="nav-number">3.</span> <span class="nav-text">旋转</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B3%E8%A1%A1%E4%BF%AE%E6%AD%A3"><span class="nav-number">4.</span> <span class="nav-text">平衡修正</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8F%92%E5%85%A5"><span class="nav-number">5.</span> <span class="nav-text">插入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#end"><span class="nav-number">6.</span> <span class="nav-text">end</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/04/08/2017-4-08-avl_tree/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          平衡查找树之AVL树
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-04-08 18:00:00" itemprop="dateCreated datePublished" datetime="2017-04-08T18:00:00+08:00">2017-04-08</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" itemprop="url" rel="index"><span itemprop="name">数据结构</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/Tree/" itemprop="url" rel="index"><span itemprop="name">Tree</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><hr>
<p><code>AVL树</code>得名于它的发明者G.M. Adelson-Velsky和E.M. Landis,它是最先发明的<code>自平衡二叉查找树</code>.</p>
<p>在<code>AVL树</code>中<strong>任何节点的两个子树的高度最大差别为一</strong>.并且,查找、插入、删除等操作在平均和最坏情况下都是<code>O(log n)</code>.</p>
<p><code>AVL树</code>的基本操作都与<code>二叉查找树</code>的算法一致,只有在插入、删除等这种会<strong>改变树的平衡性的操作需要使用一些<code>旋转操作</code>来修正树的平衡性</strong>.</p>
<h2 id="平衡因子"><a href="#平衡因子" class="headerlink" title="平衡因子"></a>平衡因子</h2><hr>
<p>节点的<code>平衡因子</code>一般是它的<code>左子树</code>的高度减去它的<code>右子树</code>的高度(相反也可以).带有<code>平衡因子</code>为1、0或-1的节点被认为是平衡的.带有<code>平衡因子</code>为-2或2的节点被认为是不平衡的.</p>
<p>计算树的高度与平衡因子的代码如下.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// calculate node x depth</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">calcDepth</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> depth = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (x.left != <span class="keyword">null</span>)</span><br><span class="line">        depth = x.left.depth;</span><br><span class="line">    <span class="keyword">if</span> (x.right != <span class="keyword">null</span> &amp;&amp; x.right.depth &gt; depth)</span><br><span class="line">        depth = x.right.depth;</span><br><span class="line">    <span class="comment">// parent + left or right depth</span></span><br><span class="line">    depth++;</span><br><span class="line">    <span class="keyword">return</span> depth;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// calculate node x balance(left.depth - right.depth)</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">calcBalance</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> leftDepth = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> rightDepth = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (x.left != <span class="keyword">null</span>)</span><br><span class="line">        leftDepth = x.left.depth;</span><br><span class="line">    <span class="keyword">if</span> (x.right != <span class="keyword">null</span>)</span><br><span class="line">        rightDepth = x.right.depth;</span><br><span class="line">    <span class="keyword">return</span> leftDepth - rightDepth;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="旋转"><a href="#旋转" class="headerlink" title="旋转"></a>旋转</h2><hr>
<p><code>旋转操作</code>是用于修复树的平衡性的,它保证了树的有序性与平衡性(旋转操作的具体讲解可以参考<a target="_blank" rel="noopener" href="http://sylvanassun.github.io/2017/03/30/red_black_binary_search_tree/">《Algorithms,4th Edition》读书笔记-红黑二叉查找树</a>).</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Node <span class="title">rotateLeft</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">    Node t = x.right;</span><br><span class="line">    x.right = t.left;</span><br><span class="line">    t.left = x;</span><br><span class="line">    <span class="keyword">if</span> (x.parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">        t.parent = x.parent;</span><br><span class="line">        <span class="keyword">if</span> (x.parent.left == x)</span><br><span class="line">            x.parent.left = t;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            x.parent.right = t;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        t.parent = <span class="keyword">null</span>;</span><br><span class="line">        root = t;</span><br><span class="line">    &#125;</span><br><span class="line">    x.parent = t;</span><br><span class="line">    <span class="comment">// calculate depth and balance</span></span><br><span class="line">    x.depth = calcDepth(x);</span><br><span class="line">    x.balance = calcBalance(x);</span><br><span class="line">    t.depth = calcDepth(t);</span><br><span class="line">    t.balance = calcBalance(t);</span><br><span class="line">    <span class="comment">// calculate size</span></span><br><span class="line">    t.size = x.size;</span><br><span class="line">    x.size = <span class="number">1</span> + size(x.left) + size(x.right);</span><br><span class="line">    <span class="keyword">return</span> t;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Node <span class="title">rotateRight</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">    Node t = x.left;</span><br><span class="line">    x.left = t.right;</span><br><span class="line">    t.right = x;</span><br><span class="line">    <span class="keyword">if</span> (x.parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">        t.parent = x.parent;</span><br><span class="line">        <span class="keyword">if</span> (x.parent.left == x)</span><br><span class="line">            x.parent.left = t;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            x.parent.right = t;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        t.parent = <span class="keyword">null</span>;</span><br><span class="line">        root = t;</span><br><span class="line">    &#125;</span><br><span class="line">    x.parent = t;</span><br><span class="line">    <span class="comment">// calculate depth and balance</span></span><br><span class="line">    x.depth = calcDepth(x);</span><br><span class="line">    x.balance = calcBalance(x);</span><br><span class="line">    t.depth = calcDepth(t);</span><br><span class="line">    t.balance = calcBalance(t);</span><br><span class="line">    <span class="comment">// calculate size</span></span><br><span class="line">    t.size = x.size;</span><br><span class="line">    x.size = <span class="number">1</span> + size(x.left) + size(x.right);</span><br><span class="line">    <span class="keyword">return</span> t;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="平衡修正"><a href="#平衡修正" class="headerlink" title="平衡修正"></a>平衡修正</h2><hr>
<p>当一个节点被认为是不平衡的时候,我们需要使用一些<code>旋转操作</code>来修正树的平衡,一般有以下情况需要进行<code>旋转</code>.</p>
<ul>
<li>例如当前节点为<code>x</code>,对<code>x</code>进行平衡修正需要进行以下判断.</li>
</ul>
<ul>
<li>当<code>x</code>的<code>平衡因子</code>大于等于2时(左子树高度偏高),对其进行<code>右旋转</code>.</li>
</ul>
<ul>
<li>当<code>x</code>的<code>左子树</code>的<code>平衡因子</code>等于-1时(左子树的右子节点高度偏高),对<code>x</code>的<code>左子树</code>进行<code>左旋转</code>.</li>
</ul>
<ul>
<li>当<code>x</code>的<code>平衡因子</code>小于等于-2时(右子树高度偏高),对其进行<code>左旋转</code>.</li>
</ul>
<ul>
<li>当<code>x</code>的<code>右子树</code>的<code>平衡因子</code>等于1时(右子树的左子节点高度偏高),对<code>x</code>的<code>右子树</code>进行<code>右旋转</code>.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">balance</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (x != <span class="keyword">null</span>) &#123;</span><br><span class="line">        x.depth = calcDepth(x);</span><br><span class="line">        x.balance = calcBalance(x);</span><br><span class="line">        <span class="comment">// if x left subtree high,rotateRight</span></span><br><span class="line">        <span class="keyword">if</span> (x.balance &gt;= <span class="number">2</span>) &#123;</span><br><span class="line">            <span class="comment">// if x.left.right high,rotateLeft</span></span><br><span class="line">            <span class="keyword">if</span> (x.left != <span class="keyword">null</span> &amp;&amp; x.left.balance == -<span class="number">1</span>) &#123;</span><br><span class="line">                x.left = rotateLeft(x.left);</span><br><span class="line">            &#125;</span><br><span class="line">            x = rotateRight(x);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// if x right subtree high,rotateLeft</span></span><br><span class="line">        <span class="keyword">if</span> (x.balance &lt;= -<span class="number">2</span>) &#123;</span><br><span class="line">            <span class="comment">// if x.right.left high,rotateRight</span></span><br><span class="line">            <span class="keyword">if</span> (x.right != <span class="keyword">null</span> &amp;&amp; x.right.balance == <span class="number">1</span>) &#123;</span><br><span class="line">                x.right = rotateRight(x.right);</span><br><span class="line">            &#125;</span><br><span class="line">            x = rotateLeft(x);</span><br><span class="line">        &#125;</span><br><span class="line">        x.size = <span class="number">1</span> + size(x.left) + size(x.right);</span><br><span class="line">        x = x.parent;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h2><hr>
<p><code>AVL树</code>的插入和删除与<code>二分查找树</code>的算法一致,只不过在完成插入后需要自底向上的修复平衡性.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">put</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (key == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;called put() with key is null.&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (value == <span class="keyword">null</span>) &#123;</span><br><span class="line">        remove(key);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    put(root, key, value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">put</span><span class="params">(Node x, K key, V value)</span> </span>&#123;</span><br><span class="line">    Node parent = x;</span><br><span class="line">    <span class="keyword">int</span> cmp = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (x != <span class="keyword">null</span>) &#123;</span><br><span class="line">        parent = x;</span><br><span class="line">        cmp = key.compareTo(x.key);</span><br><span class="line">        <span class="keyword">if</span> (cmp &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            x = x.left;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (cmp &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            x = x.right;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            x.value = value;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// if not find key,create new node</span></span><br><span class="line">    x = <span class="keyword">new</span> Node(key, value, <span class="number">1</span>, parent);</span><br><span class="line">    <span class="keyword">if</span> (parent != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (cmp &lt; <span class="number">0</span>)</span><br><span class="line">            parent.left = x;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            parent.right = x;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        root = x;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// fixup balance</span></span><br><span class="line">    balance(x);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="end"><a href="#end" class="headerlink" title="end"></a>end</h2><hr>
<ul>
<li>Author : <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a></li>
</ul>
<ul>
<li>Email : <a href="mailto:&#115;&#121;&#108;&#x76;&#97;&#110;&#x61;&#x73;&#x73;&#x75;&#x6e;&#95;&#120;&#x74;&#122;&#x40;&#x31;&#54;&#51;&#x2e;&#99;&#x6f;&#x6d;">&#115;&#121;&#108;&#x76;&#97;&#110;&#x61;&#x73;&#x73;&#x75;&#x6e;&#95;&#120;&#x74;&#122;&#x40;&#x31;&#54;&#51;&#x2e;&#99;&#x6f;&#x6d;</a></li>
</ul>
<ul>
<li>文中的完整实现代码见我的<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study">GitHub</a> &amp; <a target="_blank" rel="noopener" href="https://gist.github.com/SylvanasSun/780045c5b8705ef225eb83c58a013949">Gist</a></li>
</ul>
<ul>
<li>本文参考资料引用自<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/AVL_tree">Wikipedia</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/2017/" rel="tag"># 2017</a>
              <a href="/yuwanzi.io/tags/Algorithms/" rel="tag"># Algorithms</a>
              <a href="/yuwanzi.io/tags/Tree/" rel="tag"># Tree</a>
              <a href="/yuwanzi.io/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="tag"># 数据结构</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/03/30/2017-3-30-red_black_binary_search_tree/" rel="prev" title="《Algorithms,4th Edition》读书笔记-红黑二叉查找树">
                  <i class="fa fa-chevron-left"></i> 《Algorithms,4th Edition》读书笔记-红黑二叉查找树
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/04/13/2017-4-13-hash_table/" rel="next" title="《Algorithms,4th Edition》读书笔记-散列表">
                  《Algorithms,4th Edition》读书笔记-散列表 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
